import 'package:flutter_axrjc/datasource/network/api/KnowledgeApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/AssetBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/widget/image_picker_dialog.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';

import 'state.dart';

class PostHelpLogic extends GetxController {
  final PostHelpState state = PostHelpState();
  @override
  void onInit() {
    super.onInit();
    KnowledgeApi.getHelpTabs().then((value) {
      state.tabs.addAll(value);
    });
    refreshImg();
  }

  Future<void> addImg() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }
    CroppedFile? file = await ImageCropper().cropImage(sourcePath: a.path);
    if (file == null) {
      return;
    }
    state.originImgList.add(file.path);
    refreshImg();
  }

  void refreshImg() {
    state.imgList.clear();

    state.imgList.addAll(state.originImgList);
    state.imgList.add("add");
  }

  Future<void> post() async {
    if (state.title.value.isEmpty) {
      EasyLoading.showToast("请输入标题");
      return;
    }
    if (state.content.value.isEmpty) {
      EasyLoading.showToast("请输入内容");
      return;
    }
    if (state.currentTab.value == null) {
      EasyLoading.showToast("请选择分类");
      return;
    }
    try {
      await KnowledgeApi.postHelp(
        categoryId: "${state.currentTab.value?.helpCategoriesId}",
        imgFile: state.originImgList,
        articleContent: state.content.value,
        articleTitle: state.title.value,
        file: state.homePic.value,
      );
      EasyLoading.showToast("发布成功");
      Get.back();
    } on ApiException catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast("$e");
    }
  }

  Future<void> selectHomePic() async {
    AssetBean? a = await showSingleMedia();
    if (a == null) {
      return;
    }
    state.homePic.value = a.path;
  }
}
